<template>
  <el-dialog title="登录" :visible="true" @close="cancel">
    <el-form :rules="rules" :model="userInfo">
      <el-form-item label="账号" prop="username">
        <el-input v-model="userInfo.username" autocomplete="off" @keyup.enter.native="login"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="userInfo.password" autocomplete="off" @keyup.enter.native="login"></el-input>
      </el-form-item>
      <el-form-item label="记住密码" prop="rember">
        <el-switch v-model="rember"></el-switch>
      </el-form-item>
    </el-form>
    <div class="button">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="login">登 录</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
import { socket } from "../init";
import md5 from "js-md5";

@Component
export default class Login extends Vue {
  public $route: any;
  public $router: any;
  public $message: any;
  public userInfo = {
    username: "",
    password: "",
  };
  public rember = localStorage.getItem("rember") === "true";

  public rules = {
    username: [{ required: true, message: "请输入账号", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }]
  };

  public async login() {
    const password = md5.create().update(this.userInfo.password).hex();
    const number = await socket.login(this.userInfo.username, password, this.rember);
    if (number <= 0) {
      this.$message({
          showClose: true,
          message: `账号已锁定！`,
          type: "error"
      });
      return;
    }
    if (socket.id) {
      this.$router.push("/serviceList");
    } else {
      this.$message({
          showClose: true,
          message: `账号或密码错误，还有${ number }次机会！`,
          type: "error"
      });
    }
  }

  public cancel() {
    this.$router.go(-1);
  }
}
</script>

<style scoped>
.button {
  text-align: right;
}
</style> 